﻿using QuanLyDaiLy.Model;
using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Data.OleDb;
using System.Linq;
using System.Text;

namespace QuanLyDaiLy.Context
{
    public class CNguoiDungContext: DataContext
    {
        #region Variable
        Table<CNguoiDung> table;
        #endregion 

        #region Constructor
        public CNguoiDungContext(OleDbConnection connection)
            : base(connection)
        {
            table = GetTable<CNguoiDung>();
        }
        #endregion 

        #region Public Method
        public bool KiemTraNguoiDung(string id, string matkhau)
        {
            var query = from e in table where e.ID == id && e.MatKhau == matkhau select e;

            if (query.Count() > 0) return true;

            return false;
        }

        public void Them(CNguoiDung nguoidung)
        {
            table.InsertOnSubmit(nguoidung);
            this.SubmitChanges();
        }

        public CNguoiDung LayThongTin(string id)
        {
            var query = from e in table where e.ID == id select e;

            return query.ToList().First();
        }

        public void Xoa(string id)
        {
            var nguoidung = LayThongTin(id);

            table.DeleteOnSubmit(nguoidung);
            this.SubmitChanges();
        }

        public void CapNhat(CNguoiDung nguoidung)
        {
            try
            {
                Connection.Open();

                var command = Connection.CreateCommand();
				command.CommandText = string.Format("UPDATE NguoiDung SET MatKhau='{0}', MaPhanQuyen={1} WHERE ID='{2}'",nguoidung.MatKhau, nguoidung.MaPhanQuyen, nguoidung.ID);
                command.ExecuteNonQuery();
            }catch{}
			finally
            {
				Connection.Close();
				this.Refresh(RefreshMode.OverwriteCurrentValues, table);
            }
           
        }
        #endregion
    }
}
